<?php

 	$ip=$_GET["ip"];
 	$type=$_GET["type"];
        //error_log("ip is ".$ip."\r\n", 3, "/var/tmp/my-errors.log");
 
    //$dbserver= '571f3fb81b3da.sh.cdb.myqcloud.com'; //hk-dmc.qcloud.com
    $dbserver= "10.66.186.15";
	$dbuser= 'pear_root';
	$dbpass= 'its4pear';
	$dbname= 'shadowsocks';
	//$dbport= 6020;
    $dbport= 3306;
	$dbconnection= new mysqli($dbserver,$dbuser,$dbpass,$dbname,$dbport);
	$dbconnection->set_charset("utf8mb4");


	if (!$dbconnection)
 	{
 		error_echo(500);
		return;
 	}
        // $ip="192.168.0.1";
        if($ip=="") 
        {
           if($type=="geo") 
           {
              get_traffic_info_geo($dbconnection);
           }
           else
           {
           	   error_log("get_traffic_info\r\n", 3, "/var/tmp/my-errors.log");
               get_traffic_info($dbconnection);
               //get_traffic_info_geo($dbconnection);
           }
        }
        else 
        {
           get_traffic_info_ip($dbconnection,$ip);
           error_log("get_traffic_info_ip\r\n", 3, "/var/tmp/my-errors.log");
        }
        //error_log("You messed up!", 3, "/var/tmp/my-errors.log");

	$dbconnection->close();
	return;
	
	function get_traffic_info_ip($dbconnect,$ip)
	{
		$sql= "select fog_upload , fog_download ,fog_last_time from fog_node_info_history where fog_speed_update=1 and fog_ip='".$ip."' ORDER BY fog_last_time DESC limit 48";
                error_log($sql, 3, "/var/tmp/my-errors.log");
		$result=$dbconnect->query($sql);
	        $json = array();
		    while($row =mysqli_fetch_assoc($result))
		    {

                $json[]=$row;
		    }
		    echo json_encode($json);

	}  
    function get_traffic_info($dbconnect)
	{
		$sql= "select fog_ip,fog_upload,fog_download from fog_node_info";

                //echo $sql;
		$result=$dbconnect->query($sql);

		    //create an array
		    $json = array();
		    while($row =mysqli_fetch_assoc($result))
		    {   
                $json[]=$row;
		    }
		    echo json_encode($json);

	}

    function  get_ip_info($dbconnect,$ip)
    {
        $sql = "SELECT fog_ip_info FROM fog_node_ip_info where ip='".$ip."'";
        //echo "sql is : ".$sql."\r\n";
		$result = $dbconnect->query($sql);

		if ($result->num_rows > 0) {

		    $row = $result->fetch_assoc();
		    return   $row["fog_ip_info"];

		} else 
		{
			return "";
		}	
    }
//  http://ip.taobao.com/service/getIpInfo.php?ip=210.165.106.120
//  {"code":0,"data":{"country":"\u65e5\u672c","country_id":"JP","area":"","area_id":"","region":"","region_id":"","city":"","city_id":"","county":"","county_id":"","isp":"","isp_id":"","ip":"210.165.106.120"}}

//  table : 	id 	fog_ip_info 	fog_ip 	country 	area 	region 	city 	county 	isp 	country_id 	area_id 	region_id 	city_id 	county_id 	isp_id 	as_code 	latitude 	longitude 	hostname 	expire 


	function  insert_ip_info($dbconnect,$ip,$ip_info)
	{
		//echo  $ip;
		$sql = "INSERT INTO fog_node_ip_info (ip,fog_ip_info) VALUES ('".$ip."', '".$ip_info."')";
        //echo "sql is : ".$sql."\r\n" ;

       if ($dbconnect->query($sql) === TRUE) {
		    return TRUE;
		} else {
		    return FALSE;
		}
	}

//country , country_id , area , area_id , region , region_id , city , city_id , county , county_id , isp , isp_id , ip , 
//"中国","CN","华南","800000","广东省","440000","深圳市","440300","","-1","电信","100017","183.39.159.4",


	function  ip_info_refresh($dbconnect,$ip)
	{

        $unixtime = time();
        $expire = $unixtime - 60*60*24*30;  // a month
        //$expire = $unixtime - 60;  // a month
		$sql = "DELETE FROM fog_node_ip_info WHERE expire < ".$expire." and ip='".$ip."'";
        //echo "sql is : ".$sql."\r\n" ;


       if ($dbconnect->query($sql) === TRUE) {
		    return TRUE;
		} else {		    return FALSE;
		}
	}

/*
insert ok{
  "ip": "183.39.159.4",
  "hostname": "No Hostname",
  "city": "Shenzhen",
  "region": "Guangdong",
  "country": "CN",
  "loc": "22.5333,114.1333",
  "org": "AS4134 No.31,Jin-rong Street"
}
*/
    function  insert_ip_info_all($dbconnect,$ip,$ip_info,$ip_info_ipinfo,$ip_info_64)
	{
		//echo  $ip;

        //for($i=0 ; $i< count($ip_info['data']);$i++)
        //{
        //     echo $ip_info['data'][''];
        //}
      //   get as_code 	latitude 	longitude  from  ipinfo.io
      $sql_field="";
      $sql_value="";

      $unixtime = time();
      $de_json = json_decode($ip_info,TRUE);
      

      


      $de_json_ipinfo = json_decode($ip_info_ipinfo,TRUE);
      $location = $de_json_ipinfo['loc'];
      $as_code =  $de_json_ipinfo['org'];
      //echo $location;
      //print_r(explode(',', $location));
      $latitude= explode(',', $location)[0];
      $longitude=  explode(',', $location)[1];

     
        foreach ($de_json['data'] as $k => $v) {
          //echo $k.$de_json['data'][$k];
          //echo "\r\n";
          $sql_field = $sql_field.$k.',';
          $sql_value = $sql_value."'".$v."',";
        }
        //echo  $sql_field;
        //echo "\r\n";
        //echo  $sql_value;
        //echo "\r\n";
		$sql = "INSERT INTO fog_node_ip_info (".$sql_field."fog_ip_info ,expire,as_code,latitude,longitude ".") VALUES (".$sql_value."'".$ip_info_64."','".$unixtime."','".$as_code."','".$latitude."','".$longitude."')";
        //echo "sql is : ".$sql."\r\n" ;

       if ($dbconnect->query($sql) === TRUE) {
		    return TRUE;
		} else {
		    return FALSE;
		}
	}

	function get_traffic_info_geo($dbconnect)
	{
		$sql= "select fog_ip from fog_node_info";
		$result=$dbconnect->query($sql);

		    $json = array();
		    while($row =mysqli_fetch_assoc($result))
		    {
		    	ip_info_refresh($dbconnect,$row["fog_ip"]);

                $ip_info = base64_decode(get_ip_info($dbconnect,$row["fog_ip"]));
                //echo $ip_info."\r\n";
		    	if($ip_info=="")
		    	{
		    		$url = "http://ip.taobao.com/service/getIpInfo.php?ip=".$row["fog_ip"]; 
	                $ip_info = file_get_contents($url); 

                    // http://ipinfo.io/183.39.159.4/json
	                $url_ipinfo = "http://ipinfo.io/".$row["fog_ip"]."/json"; 
	                $ip_info_ipinfo = file_get_contents($url_ipinfo); 
	              

	                //var_dump(json_decode($data)); 
	                if(strlen($ip_info) > 100)
	                {
	                	insert_ip_info_all($dbconnect,$row["fog_ip"],$ip_info,$ip_info_ipinfo,base64_encode($ip_info));
	                }
		    	}
		    	//echo $ip_info."\r\n";
		    	//echo base64_encode($ip_info)."\r\n";
		    	//echo json_decode($ip_info)."\r\n";
		    	$json[] = json_decode($ip_info);
		    }
		    echo json_encode($json);

	}

 	function error_echo($errorcode)
 	{
 		switch ($errorcode) {
 			case 400:
 				$errormsg= 'Request failed!';
 				break;

 			case 401:
 				$errormsg= 'Username or Password error!';
 				break;
 			
 			case 402:
 				$errormsg= 'Data package has expired. Please recharge!';
 				break;

 			case 403:
 				$errormsg= 'Frequent request, retry 5 seconds later!';
 				break;

 			case 406:
 				$errormsg= 'Abnormal account, check your account status!';
 				break;

 			case 500:
 				$errormsg= 'Server internal error, try later!';
 				break;
 		}

 		$msg= json_encode(array('transactionID' => $GLOBALS['transaction'],'errorcode' => $errorcode, 'errormsg' => $errormsg ));

 		echo $msg;
 	}


?>

